package com.azunitech.intercpt.ejb;

import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * Session Bean implementation class HelloServiceImpl
 */
@Stateless(mappedName = "helloService")
@Interceptors({ContextInterceptor.class, ECBDataInterceptor.class, TestInterceptor1.class, TestInterceptor2.class})
public class HelloServiceImpl implements HelloService {
	private static Logger LOG = Logger.getLogger(HelloServiceImpl.class);
	private static String DEFAULT_NAME = "World"; 
	
	@Resource
	private SessionContext sctx;
	
	@Resource(lookup = "CF-COMMAND")
	private QueueConnectionFactory connectionFactory;
	
	@Resource(lookup = "Queue-1")
	private Queue queue;
	
	@Interceptors({ACLInterceptor.class,JMSInterceptor.class, ActiveMQInterceptor.class})
	public String greet(String name) {
		Object data = sctx.getContextData().get("SOME_KEY");
		LOG.info(data);
		//Make a queue call
		try {
			QueueConnection connection = connectionFactory.createQueueConnection();
			QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
			QueueSender qsender = session.createSender(queue);
			TextMessage msg = session.createTextMessage();
			msg.setText("hello");
			qsender.send(msg);
			connection.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String finalName = StringUtils.defaultIfEmpty(name, DEFAULT_NAME);
		String greeting =  "Hello "+finalName;
		LOG.debug(greeting);
		return greeting;
	}
}
